<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');

if ( ! function_exists('save_remote_file'))
{
    function save_remote_file($url, $file_name = '')
    {
        if ($url == '') {
            return '';
        }
        // get file
        $curl = curl_init();
    	curl_setopt($curl, CURLOPT_URL, $url); 
        curl_setopt($curl, CURLOPT_HTTPGET, 1);
    	curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $data = curl_exec($curl);
        $info = curl_getinfo($curl);
        $errno = curl_errno($curl);
        curl_close($curl);
        if ($errno == 28 || $data == '') {
            return '';
        }
        $file_name = $file_name.'-'.rand(1000000, 9999999).'_'.time();
        
        // get file ext
        switch ($info['content_type']) {
            case 'image/jpeg':
                $ext = '.jpg';
                break;
            case 'image/gif':
                $ext = '.gif';
                break;
            case 'image/png':
                $ext = '.png';
                break;
            default:
                $ext = substr($url, strrpos($url, '.')+1);
        }
        
        // create folder
        $original_path = rtrim(UPLOAD_FOLDER,'/').'/';
        $render_folder = md5($file_name);
        $subPath = substr($render_folder, -1).'/'.substr($render_folder,-3,2).'/'.substr($render_folder,-4,1);
        $path = $original_path.$subPath;
        // if not exist upload folder
        if (!@is_dir($path)) {
            if (!@mkdir($path, 0755, true)) {
                return '';
            }
        }
        $file_path = $path.'/'.$file_name.$ext;
        $result = @file_put_contents($file_path, $data);
        if ($result) {
            return $subPath.'/'.$file_name.$ext;
        }
        return '';
    }
}